from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
import os
import json
from datetime import datetime, timedelta
from django.conf import settings


@login_required
def dashboard(request):
    """分析仪表板页面"""
    return render(request, 'log_analysis/dashboard.html')


@login_required
def logs(request):
    """日志查看页面"""
    return render(request, 'log_analysis/logs.html')


@login_required
def log_viewer(request):
    """日志查看器页面"""
    return render(request, 'log_analysis/log_viewer.html')


@login_required
def file_logs(request):
    """文件日志页面"""
    return render(request, 'log_analysis/file_logs.html')


@login_required
def reports(request):
    """报告页面"""
    return render(request, 'log_analysis/reports.html')


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_system_stats():
    """获取系统统计信息"""
    try:
        # 获取系统基本信息
        import psutil
        
        # CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 内存使用情况
        memory = psutil.virtual_memory()
        memory_percent = memory.percent
        memory_used = memory.used // (1024 * 1024)  # MB
        memory_total = memory.total // (1024 * 1024)  # MB
        
        # 磁盘使用情况
        disk = psutil.disk_usage('/')
        disk_percent = (disk.used / disk.total) * 100
        disk_used = disk.used // (1024 * 1024 * 1024)  # GB
        disk_total = disk.total // (1024 * 1024 * 1024)  # GB
        
        return {
            'cpu': {
                'percent': cpu_percent,
            },
            'memory': {
                'percent': memory_percent,
                'used': memory_used,
                'total': memory_total,
            },
            'disk': {
                'percent': disk_percent,
                'used': disk_used,
                'total': disk_total,
            }
        }
    except Exception as e:
        return {
            'cpu': {'percent': 0},
            'memory': {'percent': 0, 'used': 0, 'total': 0},
            'disk': {'percent': 0, 'used': 0, 'total': 0}
        }


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def system_stats(request):
    """获取系统统计信息API"""
    try:
        stats = get_system_stats()
        return Response(stats, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_log_files(request):
    """获取日志文件列表"""
    try:
        log_dir = os.path.join(settings.BASE_DIR, 'logs')
        if not os.path.exists(log_dir):
            return Response({
                'files': []
            }, status=status.HTTP_200_OK)
        
        files = []
        for filename in os.listdir(log_dir):
            if filename.endswith('.log'):
                filepath = os.path.join(log_dir, filename)
                stat = os.stat(filepath)
                files.append({
                    'name': filename,
                    'size': stat.st_size,
                    'modified': datetime.fromtimestamp(stat.st_mtime).isoformat(),
                    'path': filepath
                })
        
        # 按修改时间排序
        files.sort(key=lambda x: x['modified'], reverse=True)
        
        return Response({
            'files': files
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_log_content(request):
    """获取日志文件内容"""
    try:
        filename = request.GET.get('filename')
        if not filename:
            return Response({
                'error': '请指定日志文件名'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        log_dir = os.path.join(settings.BASE_DIR, 'logs')
        filepath = os.path.join(log_dir, filename)
        
        if not os.path.exists(filepath):
            return Response({
                'error': '日志文件不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 读取文件内容
        lines = int(request.GET.get('lines', 100))  # 默认读取最后100行
        
        with open(filepath, 'r', encoding='utf-8') as f:
            content_lines = f.readlines()
        
        # 获取最后N行
        if lines > 0:
            content_lines = content_lines[-lines:]
        
        return Response({
            'content': ''.join(content_lines),
            'lines_count': len(content_lines),
            'total_lines': len(content_lines)
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def ajax_dashboard_data(request):
    """获取仪表板数据"""
    try:
        from apps.core.models import ProcessingTask, UploadedFile
        
        # 获取任务统计
        total_tasks = ProcessingTask.objects.count()
        pending_tasks = ProcessingTask.objects.filter(status='pending').count()
        running_tasks = ProcessingTask.objects.filter(status='running').count()
        completed_tasks = ProcessingTask.objects.filter(status='completed').count()
        failed_tasks = ProcessingTask.objects.filter(status='failed').count()
        
        # 获取文件统计
        total_files = UploadedFile.objects.count()
        
        # 获取最近7天的任务趋势
        end_date = datetime.now().date()
        start_date = end_date - timedelta(days=6)
        
        task_trend = []
        for i in range(7):
            date = start_date + timedelta(days=i)
            count = ProcessingTask.objects.filter(
                created_at__date=date
            ).count()
            task_trend.append({
                'date': date.isoformat(),
                'count': count
            })
        
        # 获取系统统计
        system_stats = get_system_stats()
        
        data = {
            'tasks': {
                'total': total_tasks,
                'pending': pending_tasks,
                'running': running_tasks,
                'completed': completed_tasks,
                'failed': failed_tasks,
                'trend': task_trend
            },
            'files': {
                'total': total_files
            },
            'system': system_stats
        }
        
        return Response(data, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def file_statistics(request):
    """获取文件统计信息"""
    try:
        from apps.core.models import UploadedFile
        
        # 获取文件类型统计
        file_types = {}
        files = UploadedFile.objects.all()
        
        for file_obj in files:
            ext = os.path.splitext(file_obj.original_filename)[1].lower()
            if ext:
                file_types[ext] = file_types.get(ext, 0) + 1
        
        # 获取文件大小统计
        total_size = sum(f.file_size for f in files)
        avg_size = total_size / len(files) if files else 0
        
        # 获取最近上传的文件
        recent_files = files.order_by('-created_at')[:10]
        
        data = {
            'total_files': len(files),
            'total_size': total_size,
            'average_size': avg_size,
            'file_types': file_types,
            'recent_files': [{
                'id': f.id,
                'name': f.original_filename,
                'size': f.file_size,
                'created_at': f.created_at.isoformat()
            } for f in recent_files]
        }
        
        return Response(data, status=status.HTTP_200_OK)
        
    except Exception as e:
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
